package com.lagou.edu.controller;

import com.lagou.edu.feign.AuthCodeFeignClient;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.TokenService;
import com.lagou.edu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Created by Heweipo on 2021/2/14.
 */
@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthCodeFeignClient authCodeFeignClient;


    /**
     * 注册接⼝，true成功，false失败
     * @param email
     * @param password
     * @param code
     * @return true/false
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable("email") String email,
                           @PathVariable("password") String password,
                           @PathVariable("code") String code){
        log.info("请求注册：email={},password={},code={}",email, password , code);

        // 验证邮箱是否重复注册
        if(isRegistered(email)){
            log.error("邮箱{}已经注册了，不能重复注册");
            return false;
        }

        // 验证 code 是否有效
        Integer validate = authCodeFeignClient.validate(email, code);
        if(validate != 0){
            log.error("验证码：{} 未通过，为：{}，不能注册",code,validate);
            return false;
        }

        // 保存用户
        User user = new User();
        user.setEmail(email);
        user.setPwd(password);
        User user1 = userService.saveUser(user);
        if(user1 != null){
            log.info("邮箱：{} 注册成功，用户: {}",email,user1);
            return true;
        }

        return false;
    }


    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，false代表尚未注册
     * @param email
     * @return true/false
     */
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email){
        log.info("请求是否已注册：email={}",email);
        return userService.isExistByEmail(email);
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和密码⽣成token，token存⼊数据库，并写⼊cookie中，登录成功返回邮箱地址，重定向到欢迎⻚
     * @param email
     * @param password
     * @return 邮箱地址
     */
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email,
                        @PathVariable("password") String password,
                        HttpServletResponse response){
        log.info("请求登录：email={},password={}",email,password);

        User user = userService.findOneByEmailAndPwd(email, password);
        if(user != null){
            log.info("邮箱：{} 登录成功",email);

            // 生成 token
            String s = UUID.randomUUID().toString();
            Token token = new Token();
            token.setToken(s);
            token.setEmail(email);
            tokenService.save(token);

            Cookie cookie = new Cookie("tokenId", s);
            cookie.setPath("/");
            //cookie.setHttpOnly(true);  //不能被js访问的Cookie
            response.addCookie(cookie);

            return email;
        }

        return null;
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     * @param token
     * @return 邮箱地址
     */
    @GetMapping("/info/{token}")
    public String validate(@PathVariable("token") String token){
        log.info("请求解析token：token={}",token);

        Token oneByToken = tokenService.findOneByToken(token);
        if(oneByToken != null){
            return oneByToken.getEmail();
        }

        return null;
    }


}
